/**
 * 微信支付 - 下单（使用标准微信支付 v3 API）
 */
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const fs = require('fs');
const config = require('../config.js');
const crypto = require('crypto');

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  
  // 从event中获取订单参数
  const { description, amount, out_trade_no, notify_url } = event;
  
  // 参数验证
  if (!description || !amount || !out_trade_no) {
    return {
      code: -1,
      msg: '缺少必要参数：description, amount, out_trade_no'
    };
  }
  
  if (!amount.total || amount.total <= 0) {
    return {
      code: -1,
      msg: '订单金额必须大于0'
    };
  }

  try {
    const openidUsed = (event && event.openid) ? event.openid : ((event && event.payer && event.payer.openid) ? event.payer.openid : wxContext.OPENID);
    console.log('[wxpay_order] 使用的 openid:', openidUsed);
    
    // 获取微信支付客户端（使用标准 wechatpay-node-v3）
    const WxPay = require('wechatpay-node-v3');
    
    // 读取证书
    const merchantPrivateKey = fs.readFileSync(config.MCH_PRIVKEY_PATH, 'utf8');
    const merchantCertPem = fs.readFileSync(config.MCH_CERT_PATH, 'utf8');
    const wechatPublicKey = fs.readFileSync(config.PLATFORM_CERT_PATH, 'utf8');
    
    // 从证书提取序列号
    let serialNo = config.SERIAL_NO;
    if (!serialNo) {
      try {
        const { Certificate } = require('@fidm/x509');
        serialNo = Certificate.fromPEM(Buffer.from(merchantCertPem)).serialNumber;
      } catch (e) {
        console.error('Failed to parse merchant certificate serial number:', e);
      }
    }
    
    const wxPay = new WxPay({
      appid: config.APPID,
      mchid: config.MCHID,
      serial_no: serialNo,
      privateKey: merchantPrivateKey,
      publicKey: wechatPublicKey,
    });
    
    // 构建请求参数
    const params = {
      appid: config.APPID,
      mchid: config.MCHID,
      description: description,
      out_trade_no: out_trade_no,
      notify_url: notify_url,
      amount: {
        total: amount.total,
        currency: amount.currency || 'CNY',
      },
      payer: {
        openid: openidUsed,
      },
    };
    
    console.log('[wxpay_order] 请求参数:', params);
    
    // 调用统一下单接口
    const result = await wxPay.transactions_jsapi(params);
    console.log('[wxpay_order] 微信支付响应:', result);
    
    const resData = result && (result.data || result);
    
    // 提取 prepay_id 并生成支付参数
    let prepayId = resData && resData.prepay_id;
    if (!prepayId && resData && typeof resData.package === 'string' && resData.package.startsWith('prepay_id=')) {
      prepayId = resData.package.replace('prepay_id=', '').trim();
    }
    
    if (!prepayId) {
      return {
        code: -1,
        msg: '微信下单失败：未返回 prepay_id',
        openid_used: openidUsed
      };
    }
    
    // 生成前端支付所需参数
    const timeStamp = String(Math.floor(Date.now() / 1000));
    const nonceStr = generateNonceStr();
    const payPackage = `prepay_id=${prepayId}`;
    
    // 生成签名
    const message = `${config.APPID}\n${timeStamp}\n${nonceStr}\n${payPackage}\n`;
    const privateKeyPem = fs.readFileSync(config.MCH_PRIVKEY_PATH, 'utf8');
    const signer = crypto.createSign('RSA-SHA256');
    signer.update(message, 'utf8');
    signer.end();
    const paySign = signer.sign(privateKeyPem, 'base64');
    
    const payParams = {
      timeStamp,
      nonceStr,
      package: payPackage,
      signType: 'RSA',
      paySign,
      openid_used: openidUsed
    };
    
    console.log('[wxpay_order] 返回支付参数');
    return {
      code: 0,
      msg: 'success',
      ...payParams
    };
  } catch (error) {
    console.error('微信支付下单失败:', error);
    return {
      code: -1,
      msg: '微信支付下单失败: ' + error.message,
    };
  }
};

// 生成随机字符串
function generateNonceStr() {
  return Math.random().toString(36).substr(2, 15);
}